<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script type="text/javascript">
        window.onload = function (ev) {
            var form = document.forms["my_form"];
            var allChild = form.children;
            //console.log(allChild.length);
            form.onsubmit = function () {
                var clzPattern = /^ *notNull *$/;
                var alertPrefix;
                for (var i = 0; i < allChild.length; i++) {
                    if (clzPattern.test(allChild[i].className)) { //class属性里面有notNull，说明要进行校验
                        if (allChild[i].value == "") {
                            alertPrefix = allChild[i].previousElementSibling.textContent;
                            alertPrefix = alertPrefix.substring(0, alertPrefix.length - 1);
                            alert(alertPrefix + "不能为空!!!");
                            return false;
                        }
                    }
                }
                return true;
            };

        }
    </script>
</head>

<body>
<form id="my_form" action="#" method="post">
    <label for="username">用户名：</label>
    <input type="text" name="username" id="username" class="  notNull  "><br/>
    <label for="password">密码：</label>
    <input type="password" name="password" id="password" class="notNull"><br/>
    <input type="submit" value="提交">
</form>

</body>
</html>
